package com.movecar.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.model.ClubBean;
import com.movecar.model.MyMenuBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zbar.lib.CaptureActivity;

/**
 * 我的
 * 
 * @author Zhao.JQ
 * 
 */
@SuppressLint("NewApi")
public class MoreActivity extends Activity implements OnClickListener {
	private ImageView user_photo;
	private CustomProgressDialog progressDialog = null;
	private MyMenuBean mMyMenuBean;
	private TextView group_order_num, coins_num, move_car_num, user_nickname;
	private ImageLoader imageLoader = null;

	private RelativeLayout main_relative, navi_new_tip_4, navi_new_tip_5, navi_new_tip_1;
	private String notifyFlag, coin_reward_share, coin_reward_praise, coin_reward_comment, coin_reward_hotShare,
			coin_exchange_recharge, coin_exchange_getCash, coin_exchange_join, coin_reward_redbag;
	private String csId;
	private boolean push = false;
	private boolean applyFriend = false;
	private TextView location_info;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.more_main);
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		initView();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initView() {
		notifyFlag = getIntent().getStringExtra("notifyFlag");
		push = getIntent().getBooleanExtra("push", false);
		applyFriend = getIntent().getBooleanExtra("push", false);
		csId = getIntent().getStringExtra("csId");
		coin_reward_share = getIntent().getStringExtra("coin_reward_share");
		coin_reward_praise = getIntent().getStringExtra("coin_reward_praise");
		coin_reward_comment = getIntent().getStringExtra("coin_reward_comment");
		coin_reward_hotShare = getIntent().getStringExtra("coin_reward_hotShare");
		coin_exchange_recharge = getIntent().getStringExtra("coin_exchange_recharge");
		coin_exchange_getCash = getIntent().getStringExtra("coin_exchange_getCash");
		coin_exchange_join = getIntent().getStringExtra("coin_exchange_join");
		coin_reward_redbag = getIntent().getStringExtra("coin_reward_redbag");
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("我的");
		user_photo = (ImageView) findViewById(R.id.user_photo);
		user_photo.setOnClickListener(this);
		findViewById(R.id.group_order).setOnClickListener(this);
		findViewById(R.id.out).setOnClickListener(this);
		findViewById(R.id.friends).setOnClickListener(this);
		findViewById(R.id.personnel_info).setOnClickListener(this);
		findViewById(R.id.install).setOnClickListener(this);
		findViewById(R.id.move_car).setOnClickListener(this);
		findViewById(R.id.capture).setOnClickListener(this);
		findViewById(R.id.info_manage).setOnClickListener(this);
		findViewById(R.id.coin).setOnClickListener(this);
		findViewById(R.id.location).setOnClickListener(this);
		findViewById(R.id.suggestion).setOnClickListener(this);
		navi_new_tip_4 = (RelativeLayout) findViewById(R.id.navi_new_tip_4);
		navi_new_tip_5 = (RelativeLayout) findViewById(R.id.navi_new_tip_5);
		navi_new_tip_1 = (RelativeLayout) findViewById(R.id.navi_new_tip_1);
		user_nickname = (TextView) findViewById(R.id.user_nickname);
		group_order_num = (TextView) findViewById(R.id.group_order_num);
		coins_num = (TextView) findViewById(R.id.coins_num);
		move_car_num = (TextView) findViewById(R.id.move_car_num);
		main_relative = (RelativeLayout) findViewById(R.id.main_relative);
		location_info = (TextView) findViewById(R.id.location_info);
		if ("applyFriend".equals(notifyFlag)) {
			navi_new_tip_4.setVisibility(View.VISIBLE);
		} else if (!"".equals(coin_reward_share) || !"".equals(coin_reward_praise) || !"".equals(coin_reward_comment)
				|| !"".equals(coin_reward_hotShare) || !"".equals(coin_exchange_recharge)
				|| !"".equals(coin_exchange_getCash) || !"".equals(coin_exchange_join)
				|| !"".equals(coin_reward_redbag)) {
			navi_new_tip_1.setVisibility(View.VISIBLE);
		} else if ("".equals(notifyFlag)) {

		} else {

		}
		if (push && !applyFriend) {
			Intent intent = new Intent();
			intent.setClass(this, MoreInfoManagelActivity.class);
			intent.putExtra("csId", csId);
			startActivity(intent);
			push = false;
		} else if (push && applyFriend) {
			Intent intent = new Intent();
			intent.setClass(this, ActivityAddFriends.class);
			startActivity(intent);
			push = false;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		startProgressDialog();
		getMyMenuDetail();
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {

		// 账号管理
		case R.id.out:
			startProgressDialog();
			logout();
			break;
		// 挪车服务
		case R.id.move_car:
			// Alert.info(this, "挪车服务");
			startActivity(new Intent(getApplicationContext(), MoveCarsActivity.class));

			break;

		// 扫一扫
		case R.id.capture:
			startActivity(new Intent(getApplicationContext(), CaptureActivity.class));
			break;

		// 个人信息
		case R.id.personnel_info:
			startActivityForResult(new Intent(getApplicationContext(), PersonalInfActivity.class), 0);
			break;
		// 订单
		case R.id.group_order:
			startActivity(new Intent(getApplicationContext(), MyorderListActivity.class));
			break;
		// 我的好友
		case R.id.friends:

			navi_new_tip_4.setVisibility(View.GONE);
			startActivity(new Intent(getApplicationContext(), ActivityAddFriends.class));
			break;
		// 吐槽
		case R.id.suggestion:

			startActivity(new Intent(getApplicationContext(), MoreSuggestionActivity.class));
			break;

		case R.id.install:
			intent = new Intent(getApplicationContext(), MoreInstallActivity.class);
			startActivity(intent);
			break;

		case R.id.info_manage:
			startActivity(new Intent(getApplicationContext(), MoreInfoManagelActivity.class));
			break;
		// 所在地
		case R.id.location:
			Intent intent_location = new Intent(getApplicationContext(), AueryAreaActivity.class);
			intent_location.putExtra("mCtity", mMyMenuBean == null ? "" : mMyMenuBean.getLocation());
			startActivityForResult(intent_location, 2);
			break;
		case R.id.coin:
			navi_new_tip_1.setVisibility(View.GONE);
			intent = new Intent(getApplicationContext(), CloudCoinsActivity.class);
			intent.putExtra("coin_reward_share", coin_reward_share);
			intent.putExtra("coin_reward_praise", coin_reward_praise);
			intent.putExtra("coin_reward_comment", coin_reward_comment);
			intent.putExtra("coin_reward_hotShare", coin_reward_hotShare);
			intent.putExtra("coin_exchange_recharge", coin_exchange_recharge);
			intent.putExtra("coin_exchange_getCash", coin_exchange_getCash);
			intent.putExtra("coin_exchange_join", coin_exchange_join);
			intent.putExtra("coin_reward_redbag", coin_reward_redbag);
			startActivity(intent);
			coin_reward_share = "";
			coin_reward_praise = "";
			coin_reward_comment = "";
			coin_reward_hotShare = "";
			coin_exchange_recharge = "";
			coin_exchange_getCash = "";
			coin_exchange_join = "";
			coin_reward_redbag = "";
			break;

		case R.id.user_photo:

			startActivityForResult(new Intent(getApplicationContext(), PersonalInfActivity.class), 0);
			break;
		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void getMyMenuDetail() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryMyMenuNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				Gson gson = new Gson();
				try {
					mMyMenuBean = gson.fromJson(result, MyMenuBean.class);
				} catch (Exception e) {
					return;
				}
				if (mMyMenuBean.getIcon().contains("default")) {
					imageLoader.displayImage(AppConfig.HOST + mMyMenuBean.getIcon(), user_photo,
							Constants.image_display_options, AppConfig.animateListener);
				} else {
					imageLoader.displayImage(AppConfig.HOST + mMyMenuBean.getIcon(), user_photo,
							Constants.image_display_options_conner, AppConfig.animateListener);
				}

				user_nickname.setText(mMyMenuBean.getNickname());
				group_order_num.setText(mMyMenuBean.getValidCount());
				coins_num.setText(mMyMenuBean.getCoin());
				move_car_num.setText(mMyMenuBean.getCarNumber());
				location_info.setText(mMyMenuBean.getLocation());
				main_relative.setVisibility(View.VISIBLE);

			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(MoreActivity.this, "与服务器连接失败，请检查网络");

			}
		}, ClubBean.class, AppConfig.USER).execute(params);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == AppConfig.REQUEST_MORE) {
			if (resultCode == RESULT_OK) {
				this.finish();
			}

		} else if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				startProgressDialog();
				getMyMenuDetail();
			}
		} else if (requestCode == 2) {

			if (resultCode == RESULT_OK) {
				location_info.setText(data.getStringExtra("result"));
			}

		}

	}

	/**
	 * 退出登录
	 * 
	 */
	@SuppressWarnings("unchecked")
	private void logout() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "logoutNew2"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				if (null != result) {

					if ("0".equals(result)) {
						Intent next = new Intent(MoreActivity.this, PhoneLoginActivity.class);
						// 清空SharedPreferences内数据，重新登录
						SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
						Editor editor = sharedPreferences.edit();// 获取编辑器
						editor.clear();
						editor.commit();// 提交修改
						// 清空DataStore
						DataStore.getInstance().setUserId("");
						DataStore.getInstance().setMobile("");
						Alert.warn(MoreActivity.this, "注销成功");
						startActivity(next);
						setResult(RESULT_OK, next);
						finish();
					} else {
						Alert.warn(MoreActivity.this, result);
					}
				} else {
					Alert.warn(MoreActivity.this, "系统异常!");
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.warn(MoreActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);

	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
